import Taro from '@tarojs/taro'
// import Amap from '@/static/lib/amap-wx'
import QQMapWX from '@/static/lib/qqmap-wx-jssdk.min.js'
import { STORE_LOCATION } from '@/store/location/action-types'
import allCity from '@/static/lib/city-data.json'
import { storeInfo, getMapReGeo, getMapGeo } from '@/api'

const TYPE = 'gcj02'
const qqmap = new QQMapWX({ key: 'QMYBZ-LRXEW-C2VR5-RUZTZ-ISL3V-REB4S' })
// const amap = new Amap.AMapWX({ key: '7bdb6f017f3c1aa9606b1a346eddd73a' })
// 小于24小时
const isGt24h = (prevTimestamp: number, timestamp: number = +new Date()) => timestamp - prevTimestamp < 86400000
const newCityList = Object.keys(allCity).map(key => {
  return {
    chars: key,
    list: allCity[key]
  }
})
const map = {
  // 位置授权状态
  async status() {
    try {
      const result = await Taro.getSetting()
      const authStatus = result.authSetting['scope.userLocation']
      if (authStatus) {
        return true
      } else {
        await Taro.authorize({ scope: 'scope.userLocation' })
        return true
      }
    } catch (e) {
      return false
    }
  },
  // 获取位置信息
  async getLocation(showLoading: boolean = false) {
    //获取位置信息  return： true获取地址成功/false获取地址失败
    const locationStatus = await this.status()
    console.log('locationStatus: ', locationStatus);
    if (locationStatus) {
      if (showLoading) {
        Taro.showLoading({
          title: '获取定位中'
        })
      }
      console.log('调用一次----')
      try {
        //获取当前的地理位置
        const getLocation = await Taro.getLocation({
          // isHighAccuracy: true,
          type: TYPE,
          // highAccuracyExpireTime: 4000
        })
        Taro.setStorageSync('LOCATION_STATUS', true)
        if (showLoading) {
          Taro.hideLoading()
        }
        return getLocation
      } catch (err) {
        console.log('err', err)
        Taro.setStorageSync('LOCATION_STATUS', false)
        Taro.hideLoading()
        // 没有授权，获取不了位置信息
        return !locationStatus
      }

    } else {
      Taro.setStorageSync('LOCATION_STATUS', false)
      Taro.hideLoading()
      // 没有授权，获取不了位置信息
      return locationStatus
    }
  },
  // POI搜索关键字
  search(params) {
    return new Promise((resolve, reject) => {
      qqmap.getSuggestion({
        page_size: 20,
        ...params,
        success(res) {
          if (res.status === 0) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail(err) {
          reject(err)
        }
      })
    })

  },
  // 获取地理位置信息和poi列表
  reverseGeocoder(params: any = {}) {
    return new Promise(async (resolve, reject) => {
      try {
        const { location } = params
        let locationInfo
        if (!location) {
          locationInfo = await this.getLocation()
        } else {
          locationInfo = location
        }
        if (locationInfo) {
          let { latitude, longitude } = locationInfo
          latitude = Number(String(latitude).slice(0, 8))
          longitude = Number(String(longitude).slice(0, 8))
          let storageCurrentLocation = Taro.getStorageSync('CURRENT_LOCATION')
          console.log('locationInfo', locationInfo, storageCurrentLocation)
          if (storageCurrentLocation && storageCurrentLocation.location.lng == longitude && storageCurrentLocation.location.lat == latitude) {
            console.log('经纬度跟上一次定位相同')
            resolve(storageCurrentLocation)
          } else {
            console.log('经纬度跟上一次定位不同')
            getMapReGeo({ location: longitude + ',' + latitude }).then(res => {
              let data = res.data.data
              // 没有信息时接口返回的都是空数组,
              // 实际经纬度跟接口返回有一定误差，所以存实际经纬度
              if (!Array.isArray(data.formattedAddress)) {
                let result = {
                  ad_info: {
                    city: data.city,
                    adcode: data.adcode,
                  },
                  address: `${data.province}${data.city}${data.district}${data.street}${data.number}`,
                  location: {
                    lng: longitude,
                    lat: latitude
                  },
                  formatted_addresses: {
                    recommend: data.formattedAddress
                  }
                }
                Taro.setStorage({
                  key: "CURRENT_LOCATION",
                  data: result
                })
                resolve(result)
              } else {
                reject()
              }
            })
          }

          // qqmap.reverseGeocoder({
          //   location: { latitude, longitude },
          //   get_poi: 1,
          //   poi_options: 'page_size=20;page_index=1',
          //   ...params,
          //   success(res) {
          //     resolve(res.result)
          //   },
          //   fail(err) {
          //     reject(err)
          //   },
          //   // complete: function (res) {
          //   //     console.log('complete: ', res);
          //   // }
          // })
        } else {
          resolve(locationInfo)
        }
      } catch (e) {
        console.log('error', e)
        reject(e)
      }
    })
  },
  // 距离计算
  calculateDistance(params = {}) {
    return new Promise((resolve, reject) => {
      qqmap.calculateDistance({
        mode: 'driving',
        ...params,
        success(res) {
          if (res.status === 0) {
            resolve(res.result)
          } else {
            Taro.showToast({
              icon: 'none',
              title: res.message
            })
            reject(res)
          }
        }
      })
    })
  },
  // 获取城市
  getCityList() {
    return new Promise((resolve, reject) => {
      resolve(newCityList)
    })
  },

  // 判断缓存有没有历史记录门店， true返回门店信息，false返回null
  historyStore() {
    const store = Taro.getStorageSync(STORE_LOCATION)
    if (store && store.storeName) {
      return store
    }
    return null
  },
  // 判断是否存在历史记录门店（24小时内&小于30km）
  async hasHistoryStore(location) {
    if (!location) return false
    const storeLocation = this.historyStore()
    let newStoreLocation: any = null
    if (storeLocation) {
      if (isGt24h(storeLocation.timestamp)) {
        const { latitude: userLatitude, longitude: userLongitude } = location
        const storeParams: any = {
          storeCode: storeLocation.storeCode,
          userLongitude,
          userLatitude
        }
        try {
          // 获取历史记录的门店，根据经纬度判断距离是否小于30km
          const result = await storeInfo(storeParams)
          const { distance } = result.data.data
          // 小于30km,使用浏览记录数据 distance-km
          if (Number(distance) < 30) {
            newStoreLocation = {
              ...result.data.data,
              timestamp: +new Date()
            }
            Taro.setStorageSync(STORE_LOCATION, newStoreLocation)
            return newStoreLocation
          } else {
            return newStoreLocation
          }
        } catch (e) {
          return newStoreLocation
        }
      } else {
        return newStoreLocation
      }
    }
    return newStoreLocation
  }
}
export {
  qqmap
}
export default map
